package mysql

import (
	"context"
	"github.com/myblogs/models"
)

type UserDao interface {
	Register(ctx context.Context, user *models.User) error
	CheckUserExist(ctx context.Context, username string) (bool, error)
	CheckEmailExist(ctx context.Context, email string) (bool, error)
	Login(ctx context.Context, req models.LoginReq) string
	GetUserName(ctx context.Context, username string) (int64, error)
}

type UserDaoImpl struct {
}

func NewUserDao() UserDao {
	return &UserDaoImpl{}
}

// 注册用户
func (u *UserDaoImpl) Register(ctx context.Context, user *models.User) error {
	return DB.Save(&user).Error
}

// 查询用户是否存在
func (u *UserDaoImpl) CheckUserExist(ctx context.Context, username string) (bool, error) {
	var user models.User
	if result := DB.Where("username = ?", username).First(&user); result.RowsAffected == 0 {
		return false, nil
	}
	return true, nil
}

// 通过邮箱查询用户是否存在
func (u *UserDaoImpl) CheckEmailExist(ctx context.Context, email string) (bool, error) {
	var user models.User
	if result := DB.Where("email = ?", email).First(&user); result.RowsAffected == 0 {
		return false, nil
	}
	return true, nil
}

// 登录
func (u *UserDaoImpl) Login(ctx context.Context, req models.LoginReq) string {
	var user models.User

	result := DB.Where("username = ?", req.Username).Or("email = ?", req.Email).First(&user)
	if result.RowsAffected == 0 {
		return ""
	}
	return user.PassWord
}
func (u *UserDaoImpl) GetUserName(ctx context.Context, username string) (int64, error) {
	var user models.User
	if result := DB.Where("username = ?", username).First(&user); result.RowsAffected == 0 {
		return 0, nil
	}
	return int64(user.UserID), nil
}
